package com.yuyu.storage.infrastructure.persisitence.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuyu.storage.domin.Do.GoodsStockDO;
import com.yuyu.storage.domin.repository.StockRepository;
import com.yuyu.storage.infrastructure.persisitence.convert.StockRepositoryConvert;
import com.yuyu.storage.infrastructure.persisitence.mapper.GoodsRepositoryMapper;
import com.yuyu.storage.infrastructure.persisitence.po.GoodsStockPO;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author
 * @version 1.0
 * @description: 仓库接口实现类
 * @date 2022/8/10 14:40
 */
@Service
@AllArgsConstructor(onConstructor = @_(@Autowired))
public class StockRepositoryImpl implements StockRepository {

    private final GoodsRepositoryMapper goodsRepositoryMapper;


    @Override
    public Long getStockByGoodsId(Long goodsId) {
            GoodsStockPO goodsStockPO = goodsRepositoryMapper.selectOne(new LambdaQueryWrapper<GoodsStockPO>().eq(GoodsStockPO::getGoodsId, goodsId));
            return goodsStockPO.getStockNum()<0? 0L:goodsStockPO.getStockNum();
    }

    @Override
    public List<GoodsStockDO> getAll() {
      return goodsRepositoryMapper.selectList(null).stream().map(StockRepositoryConvert::PO2DO).collect(Collectors.toList());
    }

    @Override
    public void rollBackStock(Long goodsIds, Long frozenNum) {
        GoodsStockPO goodsStockPO = goodsRepositoryMapper.selectOne(new LambdaQueryWrapper<GoodsStockPO>()
                .eq(GoodsStockPO::getGoodsId, goodsIds));
        goodsStockPO.setStockNum(goodsStockPO.getFrozenNum()+frozenNum);
        goodsRepositoryMapper.updateById(goodsStockPO);
    }
}
